Ext.namespace('GBIF');
GBIF.AddAssociation = function(config){
	var tpl = new Ext.XTemplate(
			'<tpl for="."><div class="search-item">'
		,	'<div style="padding:10px;">{term}</div>'
		,	'</div></tpl>'
	);
	var store = new Ext.data.JsonStore({
			url: '../../resources/api/api.php'
		,	baseParams: { 
					cmd: 'lookup'
			}
		,	root: 'records'
		,	totalProperty: 'recordCount'
		,	fields: ['term']
	});
	this.cb = new Ext.form.ComboBox({
				typeAhead: false
			,	loadingText: 'Searching...'
			,	hideTrigger: true
			,	triggerAction: 'all'
			,	tpl: tpl
			,	allowBlank: false
			,	store: store
			,	forceSelection: true
			,	width: 280
			,	minChars: 2
			,	itemSelector: 'div.search-item'
			,	listeners: {
						select: function(me, data){
							me.setValue(data.data.term);
						} 
					,	scope: this	
				}
	});
	var html = String.format("Type the known term that you wish to associate with the searched value \"{0}\".", GBIF.currentTerm);
	this.directionPanel = new Ext.Panel({	
				html: html
			,	height: 40	
	});
	Ext.apply(this, config, {
			width: 300
		,	height: 150
		,	modal: true
		,	resizable: false
		,	title: 'Add Association'
		,	bodyStyle: {
					backgroundColor: 'white'
				,	padding: '5px'
			}
		,	defaults: {
					border: false
			}
		,	items: [this.directionPanel, this.cb]
		,	buttonAlign: 'right'		
		,	buttons: [{
					text: 'Add Association'
				,	scope: this
				,	handler: function(){
						var association = this.cb.getValue();
						if(!Ext.isEmpty(association)){
							this.addRecord(GBIF.currentTerm, association);
						} else {
							GBIF.Notice.msg('Notice','Please select assocition');
						}
					}
			}, {
					text: 'Cancel'
				,	scope: this
				,	handler: function(){
						this.close();
					}	
			}]
	});
	
	GBIF.AddAssociation.superclass.constructor.call(this, config);
};
Ext.extend(GBIF.AddAssociation, Ext.Window, {
	addRecord: function(term, association){
			Ext.Ajax.request({
					url: '../../resources/api/savedSearch.php'
				,	params: { 
							cmd: 'addAssociation'			
						,	term: term
						,	association: association
					}
				,	scope: this	
				,	success: function(r){
						var o = Ext.decode(r.responseText);
						if(o.success){
							GBIF.Notice.msg('Success', 'Added association successfully.');
							this.fireEvent('afterAssocAdd', this);
							this.close();
						} else {
							GBIF.Notice.msg('Error', o.error.msg);
						}
					}
				,	failure: function(result){
						GBIF.Notice.msg('Error','Error in connection.');
					} 
			}, this);
	}
});